import React, { Component } from 'react';
import { Row, Col, Icon, Slider, message, Dropdown, Menu, Modal } from 'antd'
import 'antd/dist/antd.css'
import docCookies from '../../api/docCookies';
import Sound from 'react-sound';
import { getSongPlayerTime, } from '../../api/formatData';
import './index.scss'
import { getSongUrlData,getSongData } from '../../api';
import {
    LeftOutlined,
    PauseOutlined,
    CaretRightOutlined,
    RightOutlined
  } from '@ant-design/icons';


class MusicPlay extends Component {

    constructor(props){
        super(props);

        this.state = {
            position: "00.00",
            duration: "00.00",
            sliderValue: 0,
            audioPosition: 0,
            noVolume: false,
            volume: 50,
            songIndex: "",
            showVolumeSlider: false,
            rateFont: 1.00,
            songMode: "singerLoop",   //单曲循环(singleLoop),循环(songsLoop),随机(songsRandom)
            modalVisible: false,
        }

        docCookies.setItem("playing","STOPPED");
    }

    componentDidMount(){
        docCookies.getItem("playing");

        console.log("did mount")

        const songInfoData = JSON.parse(localStorage.getItem("songInfoData"))

    }

    playing = () => {
        docCookies.setItem("playing","PLAYING");
        this.forceUpdate()
    }

    pause = () => {
        docCookies.setItem("playing","PAUSED")
        this.forceUpdate()
    }

    mediaPlayingFinish = () => {
        docCookies.setItem("playing","STOPPED");
        this.setState({
            position:"00.00",
            duration:"00.00",
            sliderValue:0
        })
        this.forceUpdate()
    }


    handleError = (errorCode,description) => {
        message.info("音频加载失败,请重新尝试");
        docCookies.setItem("playing","PAUSED")
    }


    mediaPlaying = ( {position, duration} ) => {

        console.log("重新播放")

        let sliderPosition = position;
        let durationPosition = duration;
        this.changeAudioPosition = duration;

        let min = Math.floor(position/1000/60);
        let sec = Math.floor(position/1000%60);
        min = min<10?`0${min}`:min;
        sec = sec<10?`0${sec}`:sec;
        let durMin = Math.floor(duration/1000/60);
        let durSec = Math.floor(duration/1000%60);
        durMin = durMin<10?`0${durMin}`:durMin;
        durSec = durSec<10?`0${durSec}`:durSec;
        position = `${min}:${sec}`;
        duration = `${durMin}:${durSec}`;

        let sliderValue = Math.floor(sliderPosition/durationPosition*100);
        this.setState({
            position:position,
            duration:duration,
            sliderValue:sliderValue,
            audioPosition:sliderPosition,
        })

   }

   handleSliderChange = (value) => {
        let changeValue = (value/100)*this.changeAudioPosition;
        this.setState({
            audioPosition:changeValue
        })
   }


   resumeVolume = () => {
       this.setState({
            noVolume:false,
            volume:this.beforeVolume,
       })
   }


   noVolumeFunc = () => {
       this.beforeVolume = this.state.volume;
       this.setState({
            noVolume:true,
            volume:0
       })
   }


   handleMouseOver = () => {
        this.setState({
            showVolumeSlider:true
        })
   }

   handleMouseOut = () => {
        this.setState({
            showVolumeSlider:false
        })
   }

   handleVolumeChange = (value) => {
    this.setState({
        volume:value
       })
   }


    changePlayRate = (rate) => {
        this.setState({
            rateFont:rate
        })
    }


    changePlayMode = (mode) => {
        this.setState({
            songMode:mode
        })
    }


    showModal = () => {
        this.setState({
            modalVisible:true
        })
    }

    handleCancel = () => {
        this.setState({
            modalVisible:false
        })
    }


    handleClearItem = () => {
        localStorage.removeItem("songUrlData");
        localStorage.removeItem("songInfoData");
        this.forceUpdate()
    }


    playSong = (id, index) => {

        let storageSongUrlData = JSON.parse(localStorage.getItem("songUrlData"));
        storageSongUrlData.splice(index,1);
        localStorage.setItem("songUrlData",JSON.stringify(storageSongUrlData) );

        let storageSongInfoData=JSON.parse(localStorage.getItem("songInfoData"));
        storageSongInfoData.splice(index,1);
        localStorage.setItem("songInfoData",JSON.stringify(storageSongInfoData) );

        getSongUrlData(id).then( (res) => {
            if(res.data.code === 200) {
                let arr = [];
                let storage =  JSON.parse(localStorage.getItem("songUrlData"));
                if(!storage) {
                    arr.push(res.data.data[0])
                    localStorage.setItem('songUrlData',JSON.stringify(arr))
                } else {
                    storage.push(res.data.data[0])
                    localStorage.setItem("songUrlData",JSON.stringify(storage))
                }
                docCookies.setItem("playing","PLAYING");
                this.forceUpdate();
            }else {
                message.info("请求数据失败")
            }
        });


        getSongData(id).then( (res) => {
            if(res.data.code===200) {
                let arr = [];
                let storage =  JSON.parse(localStorage.getItem("songInfoData"));
                if(!storage) {
                    arr.push(res.data.songs[0])
                    localStorage.setItem('songInfoData',JSON.stringify(arr))
                    this.forceUpdate();
                }else {
                    storage.push(res.data.songs[0])
                    localStorage.setItem("songInfoData",JSON.stringify(storage))
                }
            }else {
                message.info("请求失败")
            }
        })

    }


    nextSong = (id) => {
        this.playSong(id,0)
    }


    preSong = (id) => {
        this.playSong(id,0)
    }



    dumpArtist = (singerId) => {
        this.props.history.push(`/artist?id=${singerId}`)
    }


    render() {

        const songUrlData = JSON.parse(localStorage.getItem("songUrlData"))
        const songInfoData = JSON.parse(localStorage.getItem("songInfoData"))

        const menu = (
            <Menu >
              <Menu.Item onClick={ ()=>this.changePlayRate(0.5) }>
                <span>0.50倍速</span>
              </Menu.Item>
              <Menu.Item onClick={ ()=>this.changePlayRate(0.75) }>
                <span>0.75倍速</span>
              </Menu.Item>
               <Menu.Item onClick={ ()=>this.changePlayRate(1.0) }>
                <span>1.00倍速</span>
              </Menu.Item>
              <Menu.Item onClick={ ()=>this.changePlayRate(1.25) }>
                <span>1.25倍速</span>
              </Menu.Item>
              <Menu.Item onClick={ ()=>this.changePlayRate(1.5) }>
                <span>1.50倍速</span>
              </Menu.Item>
              <Menu.Item onClick={ ()=>this.changePlayRate(2.0) }>
                <span>2.00倍速</span>
              </Menu.Item>
              <Menu.Item onClick={ ()=>this.changePlayRate(4.0) }>
                <span>4.00倍速</span>
              </Menu.Item>
            </Menu>
          );


        return (
            <div>
                <div>
                    <Sound
                        url={songUrlData?"http://cyq.center:8000/"+songUrlData[songUrlData.length-1].url:null}
                        playStatus={docCookies.getItem("playing")}
                        onPlaying={ ({position,duration})=>this.mediaPlaying({position,duration}) }
                        onFinishedPlaying={ ()=>this.mediaPlayingFinish() }
                        position={this.state.audioPosition}
                        onError={ (errorCode,description)=>this.handleError(errorCode,description) }
                        volume={this.state.volume}
                        playbackRate={ this.state.rateFont }
                        loop={this.state.songMode==="singerLoop"?true:false}
                    />
                </div>

                <div
                    className='music-play'
                    style={{
                        width:"100%",
                        height:"10vh",
                        lineHeight:"10vh",
                        backgroundColor:"#1F2632",
                        color:"#fff",
                        position:"fixed",
                        bottom:"0px",
                        left:"0px",
                        zIndex:"9999"
                    }}
                >
                    <div
                        className='music-play-content'
                        style={{
                            width:"980px",
                            margin:"0 auto",
                            minWidth:"1200px"
                        }}
                    >
                        <Row gutter={30}>
                            <Col style={{ float:"left" }}>
                                <Row>
                                    <Col
                                        onClick={ ()=>this.preSong(songInfoData.length > 0 && songInfoData[0].id) }
                                        style={{
                                            float:"left",
                                            cursor:"pointer"
                                        }}
                                    >
                                        <LeftOutlined style={{fontSize: '16px', marginRight:"30px"}}/>
                                    </Col>

                                    {
                                        docCookies.getItem('playing')==="PLAYING"
                                        ?
                                            <Col
                                                style={{
                                                    float:"left",
                                                    cursor:"pointer"
                                                }}
                                            >
                                                <PauseOutlined style={{fontSize: '25px', marginTop:"10px"}} onClick={ ()=>this.pause() }/>
                                            </Col>
                                        :
                                            <Col
                                                style={{
                                                    float:"left",
                                                    cursor:"pointer"
                                                }}>
                                                    <CaretRightOutlined style={{fontSize: '25px', marginTop:"10px"}} onClick={ ()=>this.playing() }/>
                                            </Col>
                                    }

                                    <Col
                                        onClick={ ()=>this.nextSong(songInfoData.length > 0 && songInfoData[0].id) }
                                        style={{
                                            float:"left",
                                            cursor:"pointer"
                                        }}>
                                            <RightOutlined style={{fontSize: '16px', marginLeft:"30px"}}/>
                                    </Col>

                                    <Col
                                        style={{
                                            clear:"both"
                                        }}>
                                    </Col>

                                </Row>

                            </Col>

                            <Col style={{ float:"left" }}>

                                <div
                                    style={{
                                        display:"inline-block",
                                        width:"35px",
                                        height:"35px",
                                        marginRight:"15px"
                                    }}
                                >
                                    {/* 歌曲图片 如果没有图片就用了一个icon */}
                                    {
                                        songInfoData && songInfoData.length > 0
                                        ?
                                        <img
                                            src={
                                                songInfoData.length > 0
                                                ?
                                                    "http://cyq.center:8000/"+songInfoData[songInfoData.length-1].picUrl
                                                :
                                                    null
                                            }
                                            style={{ width:"35px",height:"35px" }}
                                        />
                                        :
                                        <Icon type="user" style={{ fontSize:"20px" }} />
                                    }
                                </div>

                                <div style={{ display:"inline-block",verticalAlign:"middle" }}>

                                    {/* 歌曲名 */}
                                    <div style={{ lineHeight:"28px" }}>
                                        <span style={{ fontSize:"12px",marginRight:"10px",color:"#D9D9DA",cursor:"pointer" }}>
                                            {
                                                songInfoData && songInfoData.length > 0
                                                ?
                                                    songInfoData[songInfoData.length-1].name
                                                :
                                                    null
                                            }
                                        </span>
                                        <span style={{ fontSize:"12px",color:"#9B9B9B",cursor:"pointer" }}>
                                            {
                                                songInfoData && songInfoData.length > 0
                                                ?
                                                    songInfoData[songInfoData.length-1].album.albumName
                                                :
                                                    null
                                            }
                                        </span>
                                    </div>

                                    <div style={{ lineHeight:"20px",marginTop:"-10px",position:"relative" }} className='songTime'>
                                        <Slider
                                            value={this.state.sliderValue}
                                            tooltipVisible={false}
                                            onChange={ (value)=>this.handleSliderChange(value) }
                                            min={0}
                                            max={100}
                                            style={{
                                                width:"490px",
                                                marginRight:"10px",
                                                display:"inline-block",
                                                verticalAlign:"middle",color:"red"
                                            }}
                                        />

                                        <span>
                                            {/* 现在播放到几分几秒 */}
                                            {this.state.position}
                                        </span>

                                        <span>/</span>

                                        <span>
                                            {/* 总歌曲时长 */}
                                            {this.state.duration}
                                        </span>

                                    </div>

                                </div>

                            </Col>

                            <Col
                                style={{
                                    float:"left",
                                    position:"relative",
                                    cursor:"pointer"
                                }}
                                onMouseOver={ ()=>this.handleMouseOver() }
                                onMouseOut={ ()=>this.handleMouseOut() }
                            >
                                {/* 音量 */}
                                {
                                    this.state.noVolume
                                    ?
                                        <div onClick={ ()=>this.resumeVolume() }>
                                            <Icon type="sound" style={{ fontSize:"20px",verticalAlign:"middle",color:"#b7b7b7",cursor:"pointer" }} />
                                            <div style={{ fontSize:"10px",color:"#9B9B9B",position:"absolute",left:"14px",bottom:"-18px" }}>正常</div>
                                        </div>
                                    :
                                        <div onClick={ ()=>this.noVolumeFunc() }>
                                            <Icon type="sound" style={{ fontSize:"20px",verticalAlign:"middle",color:"#b7b7b7",cursor:"pointer" }} />
                                            <div style={{ fontSize:"10px",color:"#9B9B9B",position:"absolute",left:"14px",bottom:"-18px" }}>静音</div>
                                        </div>
                                }

                                {/* 音量条 */}
                                <div
                                    style={{
                                        position:"absolute",
                                        top:"-130px",
                                        left:"10px",
                                        width:"32px",
                                        height:"130px",
                                        backgroundColor:"#292929",
                                        display:this.state.showVolumeSlider?"block":"none"
                                    }}
                                >
                                    <Slider
                                        vertical={true}
                                        tooltipVisible={false}
                                        value={ this.state.volume }
                                        onChange={ (value)=>this.handleVolumeChange(value) }
                                    />
                                </div>

                            </Col>


                            {/* 倍速 */}
                            <Col style={{ float:"left",cursor:"pointer" }}>

                                <Dropdown overlay={menu} placement="topCenter">
                                    <div style={{ fontSize:"12px" }}>
                                        {this.state.rateFont.toFixed(2)}
                                        倍速
                                    </div>
                                </Dropdown>

                            </Col>


                            {/* 循环播放 */}
                            <Col style={{ float:"left",cursor:"pointer" }}>

                                {
                                    this.state.songMode === "singerLoop"
                                    ?
                                        <span className="singer_loop" style={{ verticalAlign:"middle" }} onClick={ ()=>this.changePlayMode("songsLoop") }></span>
                                    :
                                        (
                                            this.state.songMode==="songsLoop"
                                            ?
                                                <span className="songs_loop" onClick={ ()=>this.changePlayMode("songsRandom") } style={{ verticalAlign:"middle" }}></span>
                                            :
                                                <span className='songs_random' onClick={ ()=>this.changePlayMode("singerLoop") } style={{ verticalAlign:"middle" }}></span>
                                        )
                                }

                            </Col>

                            {/* 播放列表的图标 */}
                            <Col
                                style={{ float:"left",cursor:"pointer" }}
                                onClick={ ()=>this.showModal() }
                            >
                                <Icon type="database" />

                                <span style={{ fontSize:"12px",marginLeft:"15px" }}>
                                    {
                                        songInfoData && songInfoData.length || 0
                                    }
                                </span>

                            </Col>

                        </Row>

                    </div>

                </div>

                {/* 播放列表 */}
                <div>
                    <Modal
                        wrapClassName="playlist-modal"
                        title={
                            [
                                <div key="play-list" style={{ float:"left" }}>
                                    播放列表(
                                        {
                                            songInfoData && songInfoData.length || 0
                                        }
                                    )
                                </div>,
                                <div key="all-store" style={{ float:"right",marginRight:"20px",fontSize:"12px" }}>
                                    <span style={{ marginRight:"10px",cursor:"pointer" }} onClick={ ()=>this.handleClearItem()}>
                                        <Icon style={{ marginRight:"10px" }} type="delete" />
                                        清除
                                    </span>
                                </div>,
                                <div key="clear" style={{ clear:"both" }}></div>
                            ]
                        }
                        mask={false}
                        visible={this.state.modalVisible}
                        footer={null}
                        bodyStyle={{ height:"260px",overflow:"auto",backgroundColor:"#242223",color:"#CCCCCC" }}
                        onCancel={ ()=>this.handleCancel() }
                    >
                        {
                            songInfoData && songInfoData.map( (item,index,arr) => {

                                return (
                                    <div key={index} className='playlist-modal-sub'>

                                        {
                                            index === arr.length-1
                                            ?
                                            <div
                                                style={{
                                                    display:"inline-block",
                                                    width:"20px",
                                                    height:"28px",
                                                    lineHeight:"28px",
                                                    verticalAlign:"super"
                                                }}
                                            >
                                                <Icon type="caret-right" style={{ color:"#B50A0A",fontSize:"20px" }} />
                                            </div>
                                            :
                                            <div
                                                style={{
                                                    display:"inline-block",
                                                    width:"20px",
                                                    height:"28px",
                                                    lineHeight:"28px",
                                                    verticalAlign:"super"
                                                }}
                                            >
                                            </div>
                                        }

                                        <div
                                            onClick={ ()=>this.playSong(item.id,index) }
                                            style={{
                                                display:"inline-block",
                                                width:"266px",
                                                height:"28px",
                                                lineHeight:"28px",
                                                textAlign:"left",
                                                fontSize:"12px",
                                                overflow:"hidden",
                                                textOverflow:"ellipsis",
                                                whiteSpace:"nowrap",
                                                cursor:"pointer",
                                                paddingLeft:"10px"
                                            }}
                                        >
                                            {item.name}
                                        </div>

                                        <div
                                            onClick={ ()=>this.dumpArtist(item.album.albumId) }
                                            style={{
                                                display:"inline-block",
                                                width:"80px",
                                                height:"28px",
                                                lineHeight:"28px",
                                                fontSize:"12px",
                                                overflow:"hidden",
                                                textOverflow:"ellipsis",
                                                whiteSpace:"nowrap",
                                                cursor:"pointer"
                                            }}
                                        >
                                            {item.album.albumName}
                                        </div>

                                        <div
                                            style={{
                                                display:"inline-block",
                                                width:"45px",
                                                height:"28px",
                                                lineHeight:"28px",
                                                fontSize:"12px",
                                                overflow:"hidden",
                                                textOverflow:"ellipsis",
                                                whiteSpace:"nowrap",
                                                cursor:"pointer"
                                            }}
                                        >
                                            {getSongPlayerTime(item.time)}
                                        </div>

                                    </div>
                                )
                            })
                        }
                    </Modal>
                </div>
            </div>
        )
    }
}

export default MusicPlay;

